//
//  CommonAddressBookContactViewController.m
//  RSW.IOS
//
//  Created by zhaiqiuqiu on 16/12/29.
//  Copyright © 2016年 com.xtion.crm. All rights reserved.
//

#import "CommonAddressBookContactViewController.h"
#import "AddressBookContactCell.h"
#import "CommonAddressBookContactDetailViewController.h"

NSString *const CommonAddressBookContactViewControllerTitleParamKey = @"CommonAddressBookContactViewControllerTitleParamKey";

@interface CommonAddressBookContactViewController ()<XUISearchBarDelegate>
{
    RSWDataOperation *_manager;
    XMSQueueDictionary *_qdData;
}
@end

@implementation CommonAddressBookContactViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self checkSession];
    
    NSString *title = self.param[CommonAddressBookContactViewControllerTitleParamKey];
    [self setBackNavigateItemTitle:title];
    
    [self initVariable];
    [self initUI];
    
    [_manager getCommonAddressBookContactListCompletion:^(NSInteger nResult, XMSQueueDictionary *list, NSError *error)
     {
         [self requestComplete:nil funcationName:@"getCommonAddressBookContactListCompletion" result:nResult output:list error:error];
     }];
}

- (void)initVariable
{
    _manager = [[RSWDataOperation alloc]initWithDataOperationManagerDelegate:self];
    _qdData = [XMSQueueDictionary new];
    
    [self addKeyboardObserver];
}

- (void)initUI
{
    [super createTableView:XUITabelViewStyleTypePlain|XUITabelViewStyleTypeSearch];
    
    _ctable.separatorExistFollowCell = NO;
    _ctable.searchBar.delegate = self;
    _ctable.searchBar.searchfield.textInputMaxLength = 20;
    _ctable.sectionIndexColor = [UIColor grayColor];
}

-(void)viewControllerWillDealloc
{
    [super viewControllerWillDealloc];
    
    [_manager terminateRequest];
    
    [self removeObserver];
}

-(void)viewControllerTapDisappear
{
    [super viewControllerTapDisappear];
    
    [UIViewController closeKeyBoard];
}

-(void)requestComplete:(XMSDataOperationManager *)dom funcationName:(NSString *)szFuncationname result:(NSInteger)nResult output:(id)output error:(NSError *)error
{
    _bRefreshing = NO ;
    
    if([szFuncationname isEqualToString:@"getCommonAddressBookContactListCompletion"])
    {
        [self filterRequestResult:nResult defaultError:error noFilter:^(NSInteger requestResult)
         {
             switch(requestResult)
             {
                 case YES:
                 {
                     _qdData = output;
                     
                     [_ctable reloadData];
                     
                     break;
                 }
                 default:
                 {
                     [UIAlertView showErrorMsg:@"数据请求失败"];
                     break;
                 }
             }
         }];
    }
    else if([szFuncationname isEqualToString:@"getCommonAddressBookContactListCondition"])
    {
        _qdData = output;
        
        [_ctable reloadData];
    }
}

#pragma mark --
#pragma mark -- tableView delegate

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 80;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return [_qdData count];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return ((NSArray*)[_qdData getValueForIndex:section]).count;
}

- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView
{
    return [_qdData allKeys];
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 20;
}

-(UIView*)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UILabel *l =[[UILabel alloc]initWithFrame:CGRectMake(10, 0, 100, 20)];
    l.backgroundColor = [UIColor clearColor];
    l.text = [_qdData getKeyForIndex:section];
    l.textColor = [UIColor grayColor];
    l.font = [UIFont systemFontOfSize:14];
    
    UIImageView *v = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, tableView.width, 20)];
    //v.image = [[UIImage imageNamed:@"tv_sectionbackground.png"] resizeableCenterImage];
    v.backgroundColor = [UIColor whiteColor];
    [v addSubview:l];
    
    return v;
}

-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    AddressBookContactCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    if(cell == nil)
    {
        cell = [[AddressBookContactCell alloc]initWithReuseIdentifier:@"cell"];
    }
    
    CommonAddressBookContactInfo *c = [((NSArray*)[_qdData getValueForIndex:indexPath.section]) objectAtIndex:indexPath.row];
    
    cell.szTag = c.contactId;
    cell.titleLabel.text = c.userName;
    cell.contentLabel.text = c.departmentName;
    
    if(c.logoURL.length >0)
    {
        if([c.logoURL rangeOfString:ServiceDefaultHeadImageTag].location == NSNotFound)
        {
            XLGHeadImageCache *h = [XLGHeadImageDownloadQueue checkOrStartDownloadHeadImageWhenAddHeadImageURL:c.logoURL forKey:XLGHeadImageDownloadQueueEntAddressBookContact];
            if(h != nil)
                cell.headImage = h;
            else
                cell.headImage = [UIImage imageNamed:@"img_defaulthead.png"];
        }
        else
        {
            NSString *h = [c.logoURL substringFromIndex:[c.logoURL rangeOfString:ServiceDefaultHeadImageTag].length];
            cell.headImage = [UIImage imageNamed:h];
        }
    }
    else
        cell.headImage = [UIImage imageNamed:@"img_defaulthead.png"];
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    [UIViewController closeKeyBoard];
    
    CommonAddressBookContactInfo * c = [_qdData valueAtKeyArrayIndex:indexPath.section valueArrayIndex:indexPath.row];
    
    XUIViewControllerSwitchParam *p = [XUIViewControllerSwitchParam new];
    p.param[CommonAddressBookContactDetailViewControllerContactDetailParamKey] = c;
    [XUINavigationController pushViewControllerClass:[CommonAddressBookContactDetailViewController class] withSwitchParam:p];
}

#pragma mark --
#pragma mark -- search

- (BOOL)clearSearchField:(XUISearchBar *)searchbar
{
    return YES;
}

- (void)searchBar:(XUISearchBar *)searchbar textDidChange:(NSString *)searchText
{
    if(searchText.length>0)
    {
        [_manager stopRequest];
        
        //TODO
    }
    else
    {
        [_manager getCommonAddressBookContactListCompletion:^(NSInteger nResult, XMSQueueDictionary *list, NSError *error)
         {
             [self requestComplete:nil funcationName:@"getCommonAddressBookContactListCompletion" result:nResult output:list error:error];
         }];
    }
}

- (BOOL)searchBarSearchButtonClicked:(XUISearchBar *)searchbar
{
    [UIViewController closeKeyBoard];
    return YES;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
